package com.hc.springbootzookeeper.controller;

import com.hc.springbootzookeeper.service.ProductService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 分布式锁秒杀案例
 */
@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CuratorFramework client;

    @RequestMapping("reduce/{id}")
    public String reduceStock(@PathVariable int id) throws Exception {
        InterProcessMutex lock = new InterProcessMutex(client,"/product_"+id);
        try {
            lock.acquire();
            productService.reduceStock(id);
            System.out.println("秒杀成功");
            return "秒杀成功";
        }catch (Exception e){
            System.out.println("秒杀失败");
            return "秒杀失败";
        }finally {
            lock.release();
        }
    }
}
